package com.itheima.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.TokenHolder;
import com.itheima.dao.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Boolean save(Category category) {

        category.setUpdateUser(TokenHolder.getCurrentId());
        category.setCreateUser(TokenHolder.getCurrentId());
        category.setCreateTime(new Date(System.currentTimeMillis()));
        category.setUpdateTime(category.getCreateTime());
        category.setId(new Snowflake().nextIdStr());

        int insert = categoryMapper.insert(category);
        return insert>0;
    }

    @Override
    public Page<Category> getPage(Integer page, Integer pageSize) {

        Integer skip = (page-1)*pageSize;

        List<Category> categoryList = categoryMapper.getPage(skip, pageSize);

       Integer total = categoryMapper.selectTotal();

        Page<Category> categoryPage = new Page<>();

        categoryPage.setTotal(total);
       // categoryPage.setTotal(categoryList.size());
        categoryPage.setRecords(categoryList);
        categoryPage.setSize(pageSize);
        categoryPage.setCurrent(page);

        return categoryPage;

    }

    @Override
    public Boolean modifyCategory(Category category) {

        category.setUpdateUser(TokenHolder.getCurrentId());
        category.setUpdateTime(new Date(System.currentTimeMillis()));
        int update = categoryMapper.update(category);


        return  update>0;
    }

    @Override
    public Boolean deleteById(String id) {


        if( categoryMapper.selectTypeById(id)==null){
            int delete = categoryMapper.delete(id);
            return delete>0;
        }

      return false;
    }

    @Override
    public List<Category> selectAll(String type) {

        return categoryMapper.selectAll(type);
    }

    @Override
    public List<Category> selectList() {
        return categoryMapper.selectList();
    }


}
